from urllib import urlopen
from json import loads
import models
import datetime

def CalculatePageSize(total, itemsPerPage):
    result = total % itemsPerPage
    if result == 0:
        return int(total / itemsPerPage)
    else:
        return int(total / itemsPerPage) + 1
    
def GetMatchesInfo(matchIDList, apikey):
    result = []
    for matchID in matchIDList:
        match = models.Match.all().filter("matchID =", int(matchID)).get()
        if match:
            json_object = loads(match.matchData)
            try:
                playerData = loads(match.playersData)['response']
            except:
                playerData = None
        else:
            http = urlopen("http://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/v1?key={0}&match_id={1}&format=json".format(apikey, matchID))
            data = http.read()
            json_object = loads(data)
            playerList = ",".join([str(playerID['account_id'] + 76561197960265728) for playerID in json_object['result']['players'] if playerID['account_id'] and playerID['account_id'] != 4294967295])
            http = urlopen('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002?key={0}&steamids={1}&format=json'.format(apikey, playerList))
            playerData = http.read().decode('utf-8')
            models.Match(matchID = int(matchID), matchData = data, playersData = playerData, key_name = str(matchID)).put()
            playerData = loads(playerData)['response']
        json_object['result']['start_time'] = datetime.datetime.fromtimestamp(json_object['result']['start_time'])
        json_object['result']['duration'] = datetime.datetime.fromtimestamp(json_object['result']['duration'])
        for player in json_object['result']['players']:
            for steamid in playerData['players']:
                if str((player['account_id'] + 76561197960265728)) == steamid['steamid']:
                    player['details'] = steamid
        result.append(json_object['result'])
    return result

def GetUserInfo(userID, apikey):
    http = urlopen("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={0}&format=json&steamids={1}".format(apikey, userID))
    json_object = loads(http.read())
    return json_object['response']['players'][0]

def getUser(vkID):
    return models.User.all().filter("vkID =", int(vkID)).get()